package com.binfenhulian.chinaenergy.ces.manage.service.account;

import com.binfenhulian.chinaenergy.ces.utils.md5.MD5Util;
import com.github.pagehelper.Page;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import com.binfenhulian.chinaenergy.ces.manage.bean.param.PageParam;
import com.binfenhulian.chinaenergy.ces.manage.core.db.po.def.AccountPO;
import com.binfenhulian.chinaenergy.ces.manage.core.db.dao.def.IAccountDao;
import lombok.extern.slf4j.Slf4j;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.io.UnsupportedEncodingException;
import java.security.NoSuchAlgorithmException;

/**
 * Created by wanghjbuf on 2018/3/8.
 */
@Slf4j
@Service(value = "com.binfenhulian.chinaenergy.ces.manage.service.account.AccountServiceImpl")
public class AccountServiceImpl implements AccountService {
    @Resource
    IAccountDao accountDAO;

    @Override
    public AccountPO getAccountById(int id) {
        return accountDAO.selectById(id);
    }

    @Override
    public AccountPO getAccountByMobile(String mobile) {
        return accountDAO.selectByMobile(mobile);
    }

    @Override
    public int deleteAccountById(int id) {
        return accountDAO.deleteById(id);
    }

    @Override
    public int updateAccount(AccountPO account) {
        return accountDAO.update(account);
    }

    @Override
    public int addAccount(String name, String oriPassword, String mobile) {
        // 密码更新为MD的数值
        AccountPO account = new AccountPO();
        account.setName(name);
        try {
            account.setPassword(MD5Util.EncoderByMd5(oriPassword));
        } catch (NoSuchAlgorithmException e) {
            log.error("添加密码出错", e);
        } catch (UnsupportedEncodingException e) {
            log.error("添加密码出错", e);
        }
        account.setMobile(mobile);
        accountDAO.insert(account);
        return account.getId();
    }

    @Override
    public PageInfo listAccountByPage(PageParam pageParam) {
        Page page = PageHelper.startPage(pageParam.getPageNum(), pageParam.getPageSize());
        PageInfo pageInfo = new PageInfo(accountDAO.selectAll());
        return pageInfo;
    }

    @Override
    public boolean validatePassword(String mobile, String passwordForValidate) {
        AccountPO accountPO = accountDAO.selectByMobile(mobile);
        if (accountPO == null) {
            return false;
        }

        String md5 = null;
        try {
            md5 = MD5Util.EncoderByMd5(passwordForValidate);
        } catch (NoSuchAlgorithmException e) {
            log.error("验证密码出错", e);
            return false;
        } catch (UnsupportedEncodingException e) {
            log.error("验证密码出错", e);
            return false;
        }

        if (accountPO.getPassword().equals(md5)) {
            return true;
        }
        return false;
    }
}
